package edu.arizona.arid.akshen.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;

public final class FileNavigationController extends ViewController implements CommandListener {
	
	private String currDirName;

	private Command view = new Command("View", Command.OK, 1);
	private Command back = new Command("Back", Command.BACK, 2);
	private Command exit = new Command("Exit", Command.EXIT, 3);

	private final static String UP_DIRECTORY = "..";
	private final static String MEGA_ROOT = "/";
	private final static String SEP_STR = "/";
	private final static char SEP = '/';
	
	private Displayable currentDisplayable;
	
	public FileNavigationController() {
		currDirName = MEGA_ROOT;
	}
	
	public Displayable getDisplayable() {
		return currentDisplayable;
	}

	public void commandAction(Command c, Displayable d) {
		int commandType = c.getCommandType();
		if (commandType == Command.OK) {
			
			List curr = (List) d;
			final String currFile = curr.getString(curr.getSelectedIndex());
			new Thread(new Runnable() {
				public void run() {
					if (currFile.endsWith(SEP_STR)
							|| currFile.equals(UP_DIRECTORY)) {
						traverseDirectory(currFile);
					} else {
						showFile(currFile);
					}
				}
			}).start();
			
		} else if (commandType == Command.BACK) {
			showCurrDir();
		} else if (commandType == Command.EXIT) {
			//destroyApp(false);
			navigationController.destroyApp();
		}
		
	}
	
	public void showCurrDir() {
		Enumeration e;
		FileConnection currDir = null;
		List browser;
		try {
			if (MEGA_ROOT.equals(currDirName)) {
				e = FileSystemRegistry.listRoots();
				browser = new List(currDirName, List.IMPLICIT);
			} else {
				currDir = (FileConnection) Connector.open("file://localhost/"
						+ currDirName);
				e = currDir.list();
				browser = new List(currDirName, List.IMPLICIT);
				browser.append(UP_DIRECTORY, null);
			}
			while (e.hasMoreElements()) {
				String fileName = (String) e.nextElement();
				if (fileName.charAt(fileName.length() - 1) == SEP) {
					browser.append(fileName, null);
				} else {
					browser.append(fileName, null);
				}
			}
			browser.setSelectCommand(view);
			browser.addCommand(exit);
			browser.setCommandListener(this);
			if (currDir != null) {
				currDir.close();
			}
			navigationController.getDisplay().setCurrent(browser);
			currentDisplayable = browser;
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void traverseDirectory(String fileName) {
		if (currDirName.equals(MEGA_ROOT)) {
			if (fileName.equals(UP_DIRECTORY)) {
				// can not go up from MEGA_ROOT
				return;
			}
			currDirName = fileName;
		} else if (fileName.equals(UP_DIRECTORY)) {
			// Go up one directory
			// TODO use setFileConnection when implemented
			int i = currDirName.lastIndexOf(SEP, currDirName.length() - 2);
			if (i != -1) {
				currDirName = currDirName.substring(0, i + 1);
			} else {
				currDirName = MEGA_ROOT;
			}
		} else {
			currDirName = currDirName + fileName;
		}
		showCurrDir();
	}

	private void showFile(String fileName) {
		try {
			FileConnection fc = (FileConnection) Connector
					.open("file://localhost/" + currDirName + fileName);
			if (!fc.exists()) {
				throw new IOException("File does not exists");
			}
			
			// FIXME: Temporary
			if(fileName.toLowerCase().endsWith("jpg")) {
				//System.out.println("Viewing JPG image");
				//Image image = Image.createImage(fc.openInputStream());
				PictureUploadController controller = new PictureUploadController("file://localhost/" + currDirName + fileName);
				navigationController.pushViewController(controller);
			}
			else {
				//System.out.println("Viewing some file");
				InputStream fis = fc.openInputStream();
				byte[] b = new byte[1024];
				int length = fis.read(b, 0, 1024);
				fis.close();
				fc.close();
				
				TextBox tb = new TextBox("View File: " + fileName, null, 1024,
					TextField.ANY | TextField.UNEDITABLE);
			
				tb.addCommand(back);
				tb.addCommand(exit);
				tb.setCommandListener(this);

				if (length > 0) {
					tb.setString(new String(b, 0, length));
				}
				navigationController.getDisplay().setCurrent(tb);
				currentDisplayable = tb;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
